﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PFMCandidate;
using System.IO;

namespace PFMHandlers
{
    public class PFMDirectoryHandler:PFMHandler
    {
        public override byte[] Perform(Candidate aCandidate, byte[] baTarget)
        {
            FileInfo fi = null;
            FileStream fs = null;
            DirectoryInfo di = null;
            byte[] sResult = null;
            string sDest = null;

            base.Perform(aCandidate, baTarget);
            //把Byte Array的內容移到aCandidate指定的目录下
            sResult = GetProcessingData(aCandidate, baTarget);
            if (sResult != null)
            {
                if (!Directory.Exists(aCandidate.Target.Dir))
                    di = Directory.CreateDirectory(aCandidate.Target.Dir);
                fi = new FileInfo(GetTargetFileName(aCandidate));
                sDest = aCandidate.Target.Dir + "\\" + fi.Name;
                fs = System.IO.File.Open(sDest, FileMode.Create);
                try
                {
                    fs.Write(sResult, 0, sResult.Length);
                }
                finally
                {
                    fs.Close();
                }
            }
            CheckForDelete();
            return sResult;
        }

        private string GetTargetFileName(Candidate aCandidate)
        {
            string sResult = Path.GetFileName(aCandidate.Name);
            if (aCandidate.ProcessedName!=null&&aCandidate.ProcessedName!= "")
                sResult = aCandidate.ProcessedName;
            return sResult;
        }

    }
}
